﻿using System;
using System.Web;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.Security;
using System.Web.Script.Serialization;
using System.Linq;

using MvcCms.Data;
using MvcCms.Service.Filters;
using MvcCms.Service.Code.Email;
using MvcCms.Service;
using MvcCms.Store.Web.ViewModels;
using MvcCms.Data.Entities;
using MvcCms.Service.Code.Encryption;
using MvcCms.Service.Code;

using MvcCms.Store.Service;
using MvcCms.Store.Web.Code;
using MvcCms.Service.Cache;

namespace MvcCms.Store.Web.Controllers
{
    [RequireSsl(Redirect = true)]  
    public class StoreAccountController : MvcCms.Service.Code.BaseClasses.CMSControllerBase
    {
        #region Constructors
        private readonly IStoreService _storeService;
        private readonly ICacheService _cacheService;
        private readonly ShoppingCart _shoppingCart;
        private readonly IAccountService _accountService;
        public StoreAccountController(ShoppingCart shoppingCart, ICacheService cacheService, IStoreService storeService, IAccountService accountService, IZoneService zoneService, ICmsService cmsService)
            : base(cmsService, zoneService, accountService)
        {
            _storeService = storeService;
            _cacheService = cacheService;
            _shoppingCart = shoppingCart;
            _accountService = accountService;
        }
        #endregion

        private void MigrateShoppingCart(string UserName)
        {
            // Associate shopping cart items with logged-in user
            var cart = _shoppingCart.GetCart(this.HttpContext);

            cart.MigrateCart(UserName);
            Session[ShoppingCart.CartSessionKey] = UserName;
        }

        public ActionResult LogOn()
        {
            var portal = _cacheService.GetCurrentPortal();            

            var model = new LogOnViewModel
            {
                _Portal = portal,                
            };
            ViewBag.Title = "LogOn at " + portal.Name;
            return View(model);
        }

        [HttpPost]
        public ActionResult LogOn(LogOnViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    MigrateShoppingCart(model.UserName); 
                    
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "ShoppingCart");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            var portal = _cacheService.GetCurrentPortal();

            model._Portal = portal;
            ViewBag.Title = "LogOn at " + portal.Name;
            return View(model);
        }

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "StoreHome");
        }

        public ActionResult Register()
        {
            var portal = _cacheService.GetCurrentPortal();

            var model = new RegisterViewModel
            {
                _Portal = portal,
            };
            ViewBag.Title = "Register at " + portal.Name;
            return View(model);
        }

        [HttpPost]
        public ActionResult Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus;
                Membership.CreateUser(model.UserName, model.Password, model.Email, "question", "answer", true, null, out createStatus);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    MigrateShoppingCart(model.UserName); 
                    
                    FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
                    return RedirectToAction("Index", "ShoppingCart");
                }
                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }

            var portal = _cacheService.GetCurrentPortal();

            model._Portal = portal;
            ViewBag.Title = "Register at " + portal.Name;
            return View(model);
        }

        [Authorize]
        public ActionResult ChangePassword()
        {
            var portal = _cacheService.GetCurrentPortal();

            var model = new ChangePasswordViewModel
            {
                _Portal = portal,
            };
            ViewBag.Title = "Change Password at " + portal.Name;
            return View(model);
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                bool changePasswordSucceeded;
                try
                {
                    MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
                    changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            var portal = _cacheService.GetCurrentPortal();

            model._Portal = portal;
            ViewBag.Title = "Change Password at " + portal.Name;
            return View(model);
        }

        public ActionResult ChangePasswordSuccess()
        {
            var portal = _cacheService.GetCurrentPortal();

            var model = new ChangePasswordViewModel
            {
                _Portal = portal,
            };
            ViewBag.Title = "Password Changed at " + portal.Name;
            return View(model);
        }

        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
    }
}
